﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using DAO;
using DTO;
using BUS;

namespace ProductManagement
{
    public partial class frmPhanPhoi : Form
    {
        GiaoHangDTO giaoHang;
        DataTable dtGasXuatKho;
        DataTable dtVoGas;
        public frmPhanPhoi()
        {
            InitializeComponent();
        }
        public frmPhanPhoi(GiaoHangDTO _giaoHang)
        {
            InitializeComponent();
            giaoHang = _giaoHang;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // Fill data into column DaiLy
                String strQuery = "select * from DaiLy order by TenDaiLy";
                DataTable dt = DataAccess.Query(strQuery);
                (dgvBinhGas.Columns[1] as DataGridViewComboBoxColumn).DataSource = dt;
                (dgvBinhGas.Columns[1] as DataGridViewComboBoxColumn).DisplayMember = "TenDaiLy";
                (dgvBinhGas.Columns[1] as DataGridViewComboBoxColumn).ValueMember = "ID";

                // Fill data into column LoaiGas
                strQuery = "select gas.LoaiGas as IDGas, loai.TenLoai as TenLoaiGas1, loai.TenLoai &' ('&SoLuong&')' as TenLoaiGas, gas.SoLuong as SoLuong from (ChiTietXeDi as gas) LEFT JOIN (LoaiGas as loai) on gas.LoaiGas=loai.ID where gas.MaGiaoHang=" + giaoHang.Id + " order by loai.TenLoai";
                dtGasXuatKho = DataAccess.Query(strQuery);
                BindingSource bs = new BindingSource(dtGasXuatKho, null);
                (dgvBinhGas.Columns[2] as DataGridViewComboBoxColumn).DataSource = bs;
                (dgvBinhGas.Columns[2] as DataGridViewComboBoxColumn).DisplayMember = "TenLoaiGas";
                (dgvBinhGas.Columns[2] as DataGridViewComboBoxColumn).ValueMember = "IDGas";
                dgvBinhGas.Rows[0].Cells[0].Value = 1;
                txtMaGiaoHang.Text = "Mã số: " + giaoHang.Id.ToString() + " - Ngày: " + giaoHang.Ngay.ToString("dd/MM/yy hh:mm tt");
                if (giaoHang.TaiXe != "")
                    txtMaGiaoHang.Text += " - Tài xế: " + giaoHang.TaiXe;

                // Fill data into column DaiLy
                strQuery = "select dl.ID as ID, dl.TenDaiLy as TenDaiLy from DaiLy dl order by TenDaiLy";
                dt = DataAccess.Query(strQuery);
                (dgvVoBinhGas.Columns[1] as DataGridViewComboBoxColumn).DataSource = dt;
                (dgvVoBinhGas.Columns[1] as DataGridViewComboBoxColumn).DisplayMember = "TenDaiLy";
                (dgvVoBinhGas.Columns[1] as DataGridViewComboBoxColumn).ValueMember = "ID";
                strQuery = "select * from LoaiGas order by TenLoai";
                DataTable dt2 = DataAccess.Query(strQuery);
                DataRow newRow = dt2.NewRow();
                newRow["ID"] = 0;
                newRow["TenLoai"] = "Thế chân";
                dt2.Rows.InsertAt(newRow, 0);
                (dgvVoBinhGas.Columns[3] as DataGridViewComboBoxColumn).DataSource = dt2;
                (dgvVoBinhGas.Columns[3] as DataGridViewComboBoxColumn).DisplayMember = "TenLoai";
                (dgvVoBinhGas.Columns[3] as DataGridViewComboBoxColumn).ValueMember = "ID";

                strQuery = "select gas.LoaiGas as IDGas, loai.TenLoai as TenLoaiGas1, loai.TenLoai &' ('&SoLuong&')' as TenLoaiGas, gas.SoLuong as SoLuong from (ChiTietXeDi as gas) LEFT JOIN (LoaiGas as loai) on gas.LoaiGas=loai.ID where gas.MaGiaoHang=" + giaoHang.Id + " order by loai.TenLoai";

                dtVoGas = DataAccess.Query(strQuery);
                (dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).DataSource = dtVoGas;
                (dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).DisplayMember = "TenLoaiGas1";
                (dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).ValueMember = "IDGas";

                dgvVoBinhGas.Rows[0].Cells[0].Value = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không thể load form\r\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Close();
            }
        }
        private String KiemTraPhanPhoi()
        {
            String mess = "";
            int i = 0;
            int n = dgvBinhGas.Rows.Count;
            if (n == 1)
                mess += "Bảng phân phối: Chưa có dữ liệu\r\n";
            for (i = 0; i < n - 1; i++)
            {
                int flag = 0;
                for (int k = 0; k < dgvBinhGas.Rows[i].Cells.Count; k++)
                {
                    if (dgvBinhGas.Rows[i].Cells[k].Value == null)
                    {
                        mess += "Bảng phân phối: Dữ liệu ở dòng " + (i + 1) + " chưa đúng\r\n";
                        flag = 1;
                        break;
                    }
                }
                if(flag == 1)
                    continue;

                // Kiem tra du lieu trung
                flag = 0;
                for (int j = i + 1; j < n - 1; j++)
                {
                    if (dgvBinhGas.Rows[i].Cells["DaiLy1"].Value.Equals(dgvBinhGas.Rows[j].Cells["DaiLy1"].Value) == true &&
                        dgvBinhGas.Rows[i].Cells["LoaiGas1"].Value.Equals(dgvBinhGas.Rows[j].Cells["LoaiGas1"].Value) == true)
                    {
                        mess += "Bảng phân phối: Dữ liệu ở dòng " + (i + 1) + " và dòng " + (j + 1) + " trùng nhau\r\n";
                        flag = 1;
                    }
                }
                //
                if (flag == 1)
                    continue;

                int id = (int)dgvBinhGas.Rows[i].Cells[2].Value;
                int tonKho = 0;
                foreach (DataRow aRow in dtGasXuatKho.Rows)
                {
                    if ((int)aRow["IDGas"] == id)
                    {
                        tonKho = (int)aRow["SoLuong"];
                    }
                }
                int soLuong = 0;
                for (int j = 0; j < n - 1; j++)
                {
                    if ((int)dgvBinhGas.Rows[j].Cells["LoaiGas1"].Value == id)
                        soLuong += int.Parse(dgvBinhGas.Rows[j].Cells[3].Value.ToString());
                }
                if (tonKho < int.Parse(dgvBinhGas.Rows[i].Cells[3].Value.ToString()))
                {
                    mess += "Bảng phân phối: Số lượng ở dòng " + (i + 1) + " vượt quá mức cho phép\r\n";
                }
            }            
            return mess;
        }
        private String KiemTraThuHoi()
        {
            String mess = "";
            int nThuHoi = dgvVoBinhGas.Rows.Count - 1;
            for (int i = 0; i < nThuHoi; i++)
            {
                int flag = 0;
                for (int k = 0; k < dgvVoBinhGas.Rows[i].Cells.Count; k++)
                {
                    if (dgvVoBinhGas.Rows[i].Cells[k].Value == null)
                    {
                        mess += "Bảng thu hồi: Dữ liệu ở dòng " + (i + 1) + " chưa đúng\r\n";
                        flag = 1;
                        break;
                    }
                }
                if (flag == 1)
                    continue;
                flag = 0;
                for (int j = i + 1; j < nThuHoi; j++)
                {
                    if (dgvVoBinhGas.Rows[i].Cells["DaiLy2"].Value.Equals(dgvVoBinhGas.Rows[j].Cells["DaiLy2"].Value) == true &&
                        dgvVoBinhGas.Rows[i].Cells["VoPhanPhoi2"].Value.Equals(dgvVoBinhGas.Rows[j].Cells["VoPhanPhoi2"].Value) == true &&
                        dgvVoBinhGas.Rows[i].Cells["VoThuVe2"].Value.Equals(dgvVoBinhGas.Rows[j].Cells["VoThuVe2"].Value) == true)
                    {
                        mess += "Bảng thu hồi: Dữ liệu ở dòng " + (i + 1) + " và dòng " + (j + 1) + " trùng nhau\r\n";
                        flag = 1;
                    }
                }
                if (flag == 1)
                    continue;

            }
            int nPhanPhoi = dgvBinhGas.Rows.Count - 1;
            int daiLy1, loaiGas1, soLuong1;
            int daiLy2, loaiGas2, soLuong2;
            String tenDaiLy, tenLoaiGas;
            for (int i = 0; i < nPhanPhoi; i++) 
            {
                tenDaiLy = (dgvBinhGas.Rows[i].Cells["DaiLy1"] as DataGridViewComboBoxCell).FormattedValue.ToString();
                tenLoaiGas = LoaiGasDTO.GetTenGas((dgvBinhGas.Rows[i].Cells["LoaiGas1"] as DataGridViewComboBoxCell).FormattedValue.ToString());
                daiLy1 = (int)dgvBinhGas.Rows[i].Cells["DaiLy1"].Value;
                loaiGas1 = (int)dgvBinhGas.Rows[i].Cells["LoaiGas1"].Value;
                soLuong1 = int.Parse(dgvBinhGas.Rows[i].Cells["SoLuong1"].Value.ToString());
                soLuong2 = 0;
                int flag = 0;
                for (int k = 0; k < nThuHoi; k++)
                {   
                    daiLy2 = (int)dgvVoBinhGas.Rows[k].Cells["DaiLy2"].Value;
                    loaiGas2 = (int)dgvVoBinhGas.Rows[k].Cells["VoPhanPhoi2"].Value;
                    if(daiLy1==daiLy2&&loaiGas1==loaiGas2)
                    {
                        flag = 1;
                        soLuong2 += int.Parse(dgvVoBinhGas.Rows[k].Cells["SoLuong2"].Value.ToString());
                    }
                }
                if (flag == 0)
                    mess += "Phân phối [" + tenLoaiGas + "] cho [" + tenDaiLy + "] mà chưa thu hồi\r\n";
                else if (soLuong1 != soLuong2)
                {
                    mess += "Số vỏ thu hồi không bằng số vỏ [" + tenLoaiGas + "] đã phân phối cho [" + tenDaiLy + "]\r\n";
                }
            }
            for (int i = 0; i < nThuHoi; i++)
            {
                tenDaiLy = (dgvVoBinhGas.Rows[i].Cells["DaiLy2"] as DataGridViewComboBoxCell).FormattedValue.ToString();
                tenLoaiGas = LoaiGasDTO.GetTenGas((dgvVoBinhGas.Rows[i].Cells["VoPhanPhoi2"] as DataGridViewComboBoxCell).FormattedValue.ToString());
                daiLy2 = (int)dgvVoBinhGas.Rows[i].Cells["DaiLy2"].Value;
                loaiGas2 = (int)dgvVoBinhGas.Rows[i].Cells["VoPhanPhoi2"].Value;
                int flag = 1;
                for (int k = 0; k < nPhanPhoi; k++)
                {
                    daiLy1 = (int)dgvBinhGas.Rows[k].Cells["DaiLy1"].Value;
                    loaiGas1 = (int)dgvBinhGas.Rows[k].Cells["LoaiGas1"].Value;
                    if (daiLy1 == daiLy2 && loaiGas1 == loaiGas2)
                    {
                        flag = 0;
                    }
                }
                if (flag == 1)
                    mess += "Thu hồi [" + tenLoaiGas + "] của [" + tenDaiLy + "] trong khi chưa phân phối\r\n";
            }
            return mess;
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                String strError = KiemTraPhanPhoi() + KiemTraThuHoi();
                if (strError == "")
                {
                    if (MessageBox.Show("Sau khi cập nhật dữ liệu, bạn sẽ không thể khôi phục\r\nBạn có chắc chắn muốn cập nhật?\r\nChọn Yes để tiếp tục\r\nChọn No để hủy", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        List<PhanPhoiDTO> dsPhanPhoi = new List<PhanPhoiDTO>();
                        List<ThuHoiDTO> dsThuHoi = new List<ThuHoiDTO>();
                        foreach (DataGridViewRow aRow in dgvBinhGas.Rows)
                        {
                            if (aRow.Cells[1].Value != null)
                            {
                                try
                                {
                                    PhanPhoiDTO phanPhoi = new PhanPhoiDTO();                                    
                                    phanPhoi.DaiLy = (int)aRow.Cells[1].Value;
                                    phanPhoi.LoaiGas = (int)aRow.Cells[2].Value;
                                    phanPhoi.SoLuong = int.Parse(aRow.Cells[3].Value as String);
                                    phanPhoi.GiaGoc = float.Parse(aRow.Cells[4].Value as String);
                                    phanPhoi.GiaBan = float.Parse(aRow.Cells[5].Value as String);
                                    phanPhoi.ChietKhau = int.Parse(aRow.Cells[6].Value.ToString());
                                    phanPhoi.GiaBan = phanPhoi.GiaBan - phanPhoi.ChietKhau;
                                    phanPhoi.MaGiaoHang = giaoHang.Id;
                                    dsPhanPhoi.Add(phanPhoi);
                                    //PhanPhoiDAO.InsertPhanPhoi(phanPhoi);                                    
                                }
                                catch (Exception ex) { throw; }
                            }
                        }
                        foreach (DataGridViewRow aRow in dgvVoBinhGas.Rows)
                        {
                            if (aRow.Cells[1].Value != null)
                            {
                                try
                                {
                                    ThuHoiDTO thuHoi = new ThuHoiDTO();
                                    thuHoi.DaiLy = (int)aRow.Cells[1].Value;
                                    thuHoi.VoPhanPhoi = (int)aRow.Cells[2].Value;
                                    thuHoi.VoThuVe = (int)aRow.Cells[3].Value;
                                    thuHoi.SoLuong = int.Parse(aRow.Cells[4].Value as String);
                                    thuHoi.PhiDoiVo = float.Parse(aRow.Cells[5].Value as String);
                                    thuHoi.MaGiaoHang = giaoHang.Id;
                                    dsThuHoi.Add(thuHoi);
                                    //ThuHoiDAO.InsertThuHoi(thuHoi);
                                }
                                catch (Exception ex) { throw; }
                            }
                        }
                        GiaoHangBUS.HoanThanhGiaoHang(giaoHang, dsPhanPhoi, dsThuHoi);
                        //GiaoHangBUS.CapNhatGiaoHang(giaoHang.Id);
                        MessageBox.Show("Cập nhật thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        this.Close();
                    }
                }
                else
                    MessageBox.Show(strError, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin ở các cột", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            dgvBinhGas.Rows.Clear();
            dgvVoBinhGas.Rows.Clear();
            dgvGas_UserDeletedRow(sender, null);
        }

        private void btnXoa_Click_1(object sender, EventArgs e)
        {
            foreach (DataGridViewRow aRow in dgvBinhGas.Rows)
            {
                if (aRow.Selected == true)
                {
                    dgvBinhGas.Rows.Remove(aRow);
                }
            }
            foreach (DataGridViewRow aRow in dgvVoBinhGas.Rows)
            {
                if (aRow.Selected == true)
                {
                    dgvVoBinhGas.Rows.Remove(aRow);
                }
            }
            dgvGas_UserDeletedRow(sender, null);
        }
        private void dgvGas_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            try
            {
                dgvBinhGas.Rows[dgvBinhGas.Rows.Count - 1].Cells[0].Value = dgvBinhGas.Rows.Count;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void dgvGas_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            for (int i = 0; i < dgvBinhGas.Rows.Count; i++)
                dgvBinhGas.Rows[i].Cells[0].Value = i + 1;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            frmQLPhanPhoi frm = new frmQLPhanPhoi();
            frm.ShowDialog();
        }


        private void btnBack_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void dgvGas_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 3)
                {
                    int loaiGas = (int)dgvBinhGas.Rows[e.RowIndex].Cells[2].Value;
                    int tonKho = 0;
                    foreach (DataRow aRow in dtGasXuatKho.Rows)
                    {
                        if ((int)aRow["IDGas"] == loaiGas)
                        {
                            tonKho = (int)aRow["SoLuong"];
                            break;
                        }
                    }
                    int soLuong = 0;
                    int count = dgvBinhGas.Rows.Count;
                    for (int i = 0; i < count - 1; i++)
                    {
                        if (dgvBinhGas.Rows[i].Cells["LoaiGas1"].Value != null && (loaiGas == (int)dgvBinhGas.Rows[i].Cells["LoaiGas1"].Value))
                        {
                            if (dgvBinhGas.Rows[i].Cells[3].Value != null)
                                soLuong += int.Parse(dgvBinhGas.Rows[i].Cells[3].Value.ToString());
                        }
                    }
                    if (tonKho < soLuong)
                    {
                        MessageBox.Show("Số lượng vượt quá mức cho phép", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        dgvBinhGas.Rows[e.RowIndex].Cells[3].Value = 0;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnBack_Click_1(object sender, EventArgs e)
        {
            Close();
        }

        private void frmPhanPhoi_SizeChanged(object sender, EventArgs e)
        {
            dgvBinhGas.Height = (Height - 150) / 2;
            dgvVoBinhGas.Location = new Point(dgvVoBinhGas.Location.X, dgvBinhGas.Location.Y + dgvBinhGas.Height + 40);
            dgvVoBinhGas.Height = (Height - 150) / 2;
            lblVoBinhGas.Location = new Point(dgvVoBinhGas.Location.X, dgvBinhGas.Location.Y + dgvBinhGas.Height + 20);
        }

        private void btnAddRow_Click(object sender, EventArgs e)
        {
            dgvBinhGas.Rows.Add();
            dgvBinhGas.Focus();
        }

        private void dgvVoBinhGas_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 1 && e.RowIndex > -1)
                {
                    //int idDaiLy = (int)dgvVoBinhGas.Rows[e.RowIndex].Cells[1].Value;
                    //// Fill data into column LoaiGas
                    //String strQuery = "select pp.DaiLy, loai.ID as ID, loai.TenLoai &' (' & SUM(pp.SoLuong) & ')' as LoaiGas, SUM(pp.SoLuong) as SoLuong  from PhanPhoi pp left join LoaiGas loai on pp.LoaiGas=loai.ID where pp.DaiLy =" + idDaiLy + " and pp.MaGiaoHang =" + giaoHang.Id + " group by loai.ID, loai.TenLoai, pp.DaiLy";

                    //dtVoGas = DataAccess.Query(strQuery);
                    //(dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).DataSource = dtVoGas;
                    //(dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).DisplayMember = "LoaiGas";
                    //(dgvVoBinhGas.Columns[2] as DataGridViewComboBoxColumn).ValueMember = "ID";


                }
                if (e.ColumnIndex == 3 && e.RowIndex >= 0 && e.RowIndex <= dgvVoBinhGas.Rows.Count - 1)
                {
                    if ((int)dgvVoBinhGas.Rows[e.RowIndex].Cells[3].Value == 0)
                        dgvVoBinhGas.Rows[e.RowIndex].Cells[5].Value = "0";
                    else
                        dgvVoBinhGas.Rows[e.RowIndex].Cells[5].Value = null;
                }
                if (e.ColumnIndex == 4)
                {
                    int loaiGas = (int)dgvVoBinhGas.Rows[e.RowIndex].Cells[2].Value;
                    int soLuong = int.Parse(dgvVoBinhGas.Rows[e.RowIndex].Cells[4].Value.ToString());
                    int tonKho = 0;
                    foreach (DataRow aRow in dtVoGas.Rows)
                    {
                        if ((int)aRow["ID"] == loaiGas)
                        {
                            tonKho = (int)aRow["SoLuong"];
                            break;
                        }
                    }
                    if (tonKho < soLuong)
                    {
                        MessageBox.Show("Số lượng vượt quá mức cho phép", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        dgvVoBinhGas.Rows[e.RowIndex].Cells[4].Value = 0;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void dgvVoBinhGas_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            dgvVoBinhGas.Rows[dgvVoBinhGas.Rows.Count - 1].Cells[0].Value = dgvVoBinhGas.Rows.Count;
        }

        private void dgvVoBinhGas_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            for (int i = 0; i < dgvVoBinhGas.Rows.Count; i++)
                dgvVoBinhGas.Rows[i].Cells[0].Value = i + 1;
        }
    }
}
